'use strict';
const {parseNum} = require("../../utils");
const {getDefaultModelConfig} = require("../../utils/common");

module.exports = app => {
    const { STRING, INTEGER, DECIMAL, TEXT } = app.Sequelize;
    const OrderItem = app.model.define(
        'OrderItem',
        {
            id: {type: INTEGER, primaryKey: true, autoIncrement: true},
            order_id: {type: INTEGER, allowNull: false, comment: '订单ID'},
            product_id: {type: INTEGER, allowNull: false, comment: '商品ID'},
            product_sku_id: {type: INTEGER, allowNull: true, comment: '商品SKU ID'},
            product_name: {type: STRING(255), allowNull: false, comment: '商品名称'},
            product_cover: {type: STRING(500), allowNull: true, comment: '商品封面'},
            sku_spec: {type: TEXT, allowNull: true, comment: 'SKU规格信息，JSON格式'},
            price: {
                type: DECIMAL(10, 2),
                defaultValue: 0.00,
                comment: '商品单价',
                get() {
                    return parseNum(this.getDataValue('price'));
                }
            },
            count: {type: INTEGER, defaultValue: 1, comment: '购买数量'},
            total_amount: {
                type: DECIMAL(10, 2),
                defaultValue: 0.00,
                comment: '小计金额',
                get() {
                    return parseNum(this.getDataValue('total_amount'));
                }
            },
            ...getDefaultModelConfig(app)
        },
        {
            tableName: 'order_item',
            timestamps: true,
            createdAt: 'create_time',
            updatedAt: 'update_time'
        }
    );

    OrderItem.associate = function() {
        app.model.Business.OrderItem.belongsTo(app.model.Business.Order, {as: 'order', foreignKey: 'order_id'});
        app.model.Business.OrderItem.belongsTo(app.model.Business.Product, {as: 'product', foreignKey: 'product_id'});
        app.model.Business.OrderItem.belongsTo(app.model.Business.ProductSku, {as: 'productSku', foreignKey: 'product_sku_id'});
    }
    
    return OrderItem;
}; 